﻿import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
    userInfo: undefined,
    configuration: undefined,
    token: ''
}

/**
 * mutations 里面放置的是我们操作state对象属性的方法
 */
const mutations = {
    setUserInfo(state, userInfo) {
        setCache('userInfo', userInfo);
        return (state.userInfo = userInfo)
    },
    setConfiguration(state, configuration) {
        setCache('configuration', configuration);
        return (state.configuration = configuration)
    },
    setToken(state, token) {
        setCache('token', token);
        return (state.token = token)
    },
    clearAll(state) {
        setCache('userInfo', undefined);
        setCache('configuration', undefined);
        setCache('token', undefined);
    }
}

const getters = {
    getUserInfo(state) {
        //if (!state.userInfo) {
        //    state.userInfo = getCache('userInfo');
        //}
        if (state.configuration) {
            return state.configuration.currentUser;
        }
        return {};
    },
    getConfiguration(state) {
        if (!state.configuration) {
            state.configuration = getCache('configuration');
        }
        return state.configuration;
    },
    getToken(state) {
        if (!state.token) {
            state.token = getCache('token');
        }
        return state.token;
    }
}

function setCache(key, val) {
    if (val) {
        localStorage.setItem('_VUE_STORE_' + key, JSON.stringify(val));
    } else {
        localStorage.removeItem('_VUE_STORE_' + key);
    }
}

function getCache(key) {
    var val = localStorage.getItem('_VUE_STORE_' + key);
    try {
        if (val) {
            return JSON.parse(val);
        } else {
            return undefined;
        }
    } catch (e) {
        //console.log('JSON解析出现异常', e);
        return undefined;
    }
}

export default new Vuex.Store({
    state,
    mutations,
    getters
})